﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.View == "undefined") Axis.View = {};
if (typeof Axis.View.Research == "undefined") Axis.View.Research = {};
var _globalEndate = "";
var MEMBER_ID = $.GetCookie("MemberID");
Axis.View.Research.List = {
    Init: function () {

        //        $('.content_9').parent().hide();
        //       $('.content_10').parent().hide();

        var thisObj = this;
        setTimeout(function () {
            thisObj.Isotope.Init();
            var ID = $.GetURL("ID");
            if (ProjectID != 0)
                ID = ProjectID;
            if (ID) {
                $(".research_item[data-id='" + ID + "']").find(".title a").trigger("click");
            }
        }, 1000);
        var projectID = $($('.research_item_preview')[0]).attr('data-id');
        thisObj.GetCloundTag(projectID);


        TextTruncate();
    },

    Isotope: {
        Count: -1,
        Container: "#Panel_Research_List",
        UpdateSortData: function (dataID) {
            var thisObj = this;
            var $container = $(thisObj.Container);
            var $research_item = $(".research_item[data-id='" + dataID + "']");
            var listzorderpreviewtofull = [0, 1, 2, 6, 8, 7, 5, 3, 4, 9];
            var listzorderfulltopreview = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
            //Khi nhan vao item dang full thi thu lai
            if ($research_item.hasClass("research_item_full")) {

                $("#Panel_Research_List").css({
                    "max-height": "900px"
                });

                $research_item.toggleClass('research_item_full research_item_preview');
                $(".research_item").each(function () {
                    if ($(this).find('.content').attr('orgClass') == "content_10") {
                        //An vi tri so 10, reset lai number, class content
                        $(this).attr("row-num", 10);
                        $(this).find(".content").toggleClass($(this).find(".content").attr("curClass") + ' ' + $(this).find(".content").attr("orgClass"));
                        $(this).hide();

                    }
                    else if ($(this).find('.content').attr('orgClass') == 'content_9') {
                        //An vi tri so 9, reset lai number, class content
                        $(this).attr("row-num", 9);
                        $(this).find(".content").toggleClass($(this).find(".content").attr("curClass") + ' ' + $(this).find(".content").attr("orgClass"));
                        //      $(this).hide();

                    }
                    else if ($(this).hasClass("content_tag")) {
                        $(this).attr("row-num", 2.5);
                        $(this).show();
                    }
                    else
                        if ($(this).hasClass("content_search")) {
                            $(this).attr("row-num", 2.6);
                            $(this).show();
                        }
                        else {
                            $(this).attr("row-num", $(this).attr("zorder"));
                            $(this).find(".content").toggleClass($(this).find(".content").attr("curClass") + ' ' + $(this).find(".content").attr("orgClass"));
                            $(this).find(".content").attr('curClass', $(this).find(".content").attr("orgClass"));
                            //remove het tat ca class detail
                            $(this).find(".content").removeClass('detail');
                        }
                });
            }
            else {

                var classcontent = "", classOrder;
                for (var i = 0; i < 11; i++) {
                    if ($research_item.find(".content").hasClass("content_" + i)) {
                        classcontent = "content_" + i;
                    }
                }
                $research_item.find(".content").toggleClass('content_1 ' + classcontent);
                $research_item.find(".content").attr('curClass', 'content_1');
                classOrder = $research_item.attr("row-num");
                $(".research_item").each(function () {
                    if ($(this).attr("row-num") == 1) {
                        $(this).attr("row-num", classOrder);
                        $(this).find(".content").toggleClass('content_1 ' + classcontent);
                        $(this).find(".content").attr('curClass', classcontent);
                    }
                });
                //set lai vi tri 1
                $research_item.attr("row-num", 1);
                $(".research_item").each(function () {
                    if ($(this).hasClass("research_item_full")) {
                        $(this).toggleClass('research_item_full research_item_preview');
                    }
                });
                $(".research_item").each(function () {
                    if ($(this).find('.content').attr('orgClass') == "content_10") {
                        //show vi tri so 10
                        $(this).show();
                        $(this).find('.content').addClass('detail');
                    }
                    if ($(this).find('.content').attr('orgClass') == "content_9") {
                        //show vi tri so 9
                        $(this).show();
                        $(this).find('.content').addClass('detail');
                    }
                    else if ($(this).hasClass("content_tag")) {
                        $(this).attr("row-num", 3.5); //11
                        //     $(this).hide();
                        $("#Panel_Research_List").css({
                            "max-height": "1800px"
                        });
                    }
                    else
                        if ($(this).hasClass("content_search")) {
                            $(this).attr("row-num", 3.6); //12
                            //       $(this).hide();
                        }
                        else {
                            $(this).find(".content").addClass('detail');
                        }
                });

                $research_item.toggleClass('research_item_preview research_item_full');
            }

            $container.isotope('updateSortData', $(".research_item"));
            $container.isotope('reLayout');
            $container.isotope({ sortBy: "zOrder" });
            $research_item.find(".content-main").removeClass("loading");
            $('html, body').animate({
                scrollTop: $("#Panel_Research_List").offset().top - 100
            }, 2000);

            thisObj.Count--;
        },
        Init: function () {
            var thisObj = this;
            var $container = $(thisObj.Container);
            $container.isotope({

                itemSelector: '.research_item',
                // disable resizing
                resizable: false,
                // set columnWidth to a percentage of container width
                masonry: {
                    columnWidth: 5,
                    rowHeight: 5
                },
                sortBy: 'zOrder',
                getSortData: {
                    zOrder: function ($elem) {
                        var re = parseFloat($elem.attr('row-num'), 10);
                        return re;
                    }
                }

            });

            $container.delegate('.research_item .title a,.research_item .content-asset a', 'click', function () {
                var $this = $(this);
                var dataID = $this.attr("data-id");
                var $research_item = $(".research_item[data-id='" + dataID + "']");
                var endDate = $research_item.attr("EndDate");
                var mark = $research_item.attr("mark");
                $research_item.find(".content-main").addClass("loading");
                var BINH_CHON_6SAO = $.GetCookie("BINH_CHON_6SAO");

                var keyVote = $.string.Format("{0}_{1}", dataID, MEMBER_ID);
                if ($research_item.hasClass("research_item_full")) {
                    thisObj.UpdateSortData(dataID);
                }
                else {
                    if (BINH_CHON_6SAO && BINH_CHON_6SAO.indexOf(keyVote) != -1) {
                        //thisObj.UpdateSortData(dataID);
                        //Axis.View.Research.List.Chart.Load(dataID);
                        //Axis.View.Research.List.GetCloundTag(GetCloundTag);
                        //$research_item.find(".content-main").removeClass("loading");
                        location.href = "../../Views/Research/ResearchDetail.aspx?ID=" + dataID;
                    }
                    else {
                        Axis.View.Research.List.GetQuestionByID(dataID, function (info) {
                            $(".research_list_question").html("");
                            //delay cho vui
                            setTimeout(function () {
                                thisObj.UpdateSortData(dataID);
                                $research_item.find(".content_detail").html(info);
                                setTimeout(function () {
                                    $("#enddate").text(_globalEndate);
                                }, 2000);
                                $research_item.find(".content-main").removeClass("loading");
                                var col_count = $("ul.research_list_question li.question_label_col").size() + 1;
                                setTimeout(function () {
                                    var li_size = $research_item.find(".content_detail .research_list_question li.question_label_col").size();
                                    var li_width = (340 / li_size) - 2;
                                    $research_item.find(".content_detail .research_list_question li").width(li_width);
                                }, 1000);
                                _globalEndate = endDate;
                                $research_item.find(".content_detail ._mark strong").text(mark);
                                // $research_item.find(".content_detail ._endDate span.last").text(endDate);
                                $("#enddate").text(endDate)
                            }, 3000);

                            setTimeout(function () {
                                $("#enddate").text(endDate);
                            }, 10000);
                        });
                    }
                }
            });
        }
    },
    GenarateQuestion: function (ResearchQues, callback) {
        if (ResearchQues) {
            var QuesHeader = '<li class="question_label_row">&nbsp;</li>';
            for (var i = 1; i < ResearchQues.QuesRow.length; i++) {
                var item = ResearchQues.QuesRow[i];
                QuesHeader += $.string.Format('<li  class="question_label_col boldHeader">{0}</li>', item.QuestionText);
            };
            var QuesContent = '';
            var QuesType = ResearchQues.QuesType || '0';
            var ProjectID = ResearchQues.ProjectID;
            $.each(ResearchQues.QuesCol, function (index, item) {
                if (index == 0)
                    QuesContent += '<li class="newline header">&nbsp;</li>';
                else
                    QuesContent += '<li class="newline">&nbsp;</li>';
                QuesContent += $.string.Format('<li class="question_label_row">{0}</li>', item.Caption);
                for (var i = 1; i < ResearchQues.QuesRow.length; i++) {
                    var Row = ResearchQues.QuesRow[i];
                    if (QuesType == "1") {
                        QuesContent += $.string.Format('<li>'
                        + '<input type="radio" id="chk_q_{0}_{1}" class="regular-radio big-radio" matrix="Research" Row="{2}" value="{1}" name="RadioResearch-{3}" />'
                        + '<label for="chk_q_{0}_{1}"></label>'
                        + '</li>', i, item.Value, Row.ID, item.ID);

                        //  QuesHeader = "";
                    }
                    else {
                        QuesContent += $.string.Format('<li>'
                        + '<input type="checkbox" id="chk_q_{0}_{1}" class="regular-checkbox big-checkbox" matrix="Research" Row="{2}" value="{1}" />'
                        + '<label for="chk_q_{0}_{1}"></label>'
                        + '</li>', i, item.Value, Row.ID);
                    }

                };
            });
            if (typeof callback == "function") {
                var ret = '';
                if (ResearchQues.QuesKey) {
                    var captcha = "<div><img src='/views/Captcha/ImageCaptcha.ashx' /><input type='text' /></div>";
                    ret += ''
                        + '<div style="clear:both;overflow:hidden;">'
                        + '<div class="_mark">Điểm tích lũy: <strong>100</strong></div>'
                        + '<div class="_endDate"><span>Ngày kết thúc:</span> <span id="enddate">31/01/2013</span></div> '
                    + '</div>'
                    + '<div class="research_detail_title">BÌNH CHỌN</div>'
                    + '<div class="question_container">'
                        + '<ul class="research_list_question" QuesType="' + QuesType + '">'
                            + QuesHeader
                            + QuesContent
                        + '</ul>'
                    + '</div>'
                     + '<div style="float:left;margin-right:15px; margin-top:10px;">'
                        + '<img class="img_research_captcha" src="/views/Captcha/ImageCaptcha.ashx" />'
                        + '<img class="imgCaptchaRefresh" src="/Images/img.icon/refresh_32x32.png" onclick="ResearchCaptchaRefresh(this);" style="cursor:pointer;"  />'

                    + '</div>'
                    + '<div style="margin-right:0px; margin-top:10px;" class="action_save_binhchon">'
                    + '<input type="text" class="research_captcha" style="width:197px;" />'
                    // + '<br />Xem kết quả khảo sát<button type="button" class="button btnResearchSave project-button" onclick="SaveServey(\'' + ResearchQues.QuesKey + '\',\'' + ResearchQues.ProjectID + '\')">Gửi</button>'
                    + '<br /><a id="viewResult" href="ResearchDetail.aspx?ID=' + ResearchQues.ProjectID + '"  >Xem kết quả khảo sát</a><button type="button" class="button btnResearchSave project-button" onclick="SaveServey(\'' + ResearchQues.QuesKey + '\',\'' + ResearchQues.ProjectID + '\')">Gửi</button>'
                    + '</div>';

                    // + '<br /><a id="viewResult" href="ResearchDetail.aspx?ID=' + ResearchQues.ProjectID + '"  >Xem kết quả khảo sát</a><button type="button" class="button btnResearchSave project-button" onclick="SaveServey(\'' + ResearchQues.QuesKey + '\',\'' + ResearchQues.ProjectID + '\')">Gửi</button>'
                }
                callback(ret);
            }
        }
        // Axis.View.Research.List.ScrollTo();
    },
    GetQuestionByID: function (pID, callback) {
        $.Ajax({
            url: "../Research/Service/ResearchService.asmx/GetQuestionByID",
            type: 'POST',
            data: { pID: pID },
            beforeSend: function () {
            },
            success: function (data, textStatus, xhr) {
                if (data) {
                    data = $.findInXml(data);
                    data = eval("(" + data + ")");
                    data.ProjectID = pID;
                    Axis.View.Research.List.GenarateQuestion(data, callback);
                }
            },
            error: function (xhr, textStatus, errorThrown) { }
        });
    },
    SaveServey: function (pQuesKey, pID) {
        var thisObj = this;
        var $research_item = $(".research_item[data-id='" + pID + "']");
        var captchaCode = $research_item.find("input.research_captcha").val();
        var data = { ProjectID: pID, pCaptcha: captchaCode };
        var ret = "";
        var QuesType = $research_item.find('.research_list_question').attr("QuesType") || "0";
        ret += "{ResponseOption:[";
        if (QuesType == "1") {
            $research_item.find(".research_list_question input[type='radio']:checked").each(function () {
                ret += "{";
                ret += $.string.Format("QuestionID:'{0}',", $(this).attr('row'));
                ret += $.string.Format("QuestionType:'{0}'", QuesType);
                ret += $.string.Format(",ResponseValue:'{0}'", $(this).val());
                ret += $.string.Format(",ResponseText:'{0}'", '');
                ret += "},";
            });

        }
        else {
            $research_item.find('.research_list_question input:checkbox[matrix="Research"]:checked').each(function () {
                ret += "{";
                ret += $.string.Format("QuestionID:'{0}',", $(this).attr('row'));
                ret += $.string.Format("QuestionType:'{0}'", 5);
                ret += $.string.Format(",ResponseValue:'{0}'", $(this).val());
                ret += $.string.Format(",ResponseText:'{0}'", '');
                ret += "},";
            });
        }

        if (ret != "{ResponseOption:[")
            ret = ret.substr(0, ret.length - 1);
        ret += "]}";
        if (ret == "" || ret == '{ResponseOption:[]}') {
            $.CAlert.Alert({
                Title: "Chưa hoàn thành bình chọn",
                Content: "Xin vui lòng chọn phương án bình chọn"
            }, function () {

            });

            return;
        }
        data.IsCompleted = 1;
        data.Action = 'INSERT';
        data.ResponseOption = ret;
        data.Browser = obs(pstfgrpnt());
        $.Ajax({
            url: '../Project/Service/ServeyService.ashx',
            type: 'POST',
            data: data,
            success: function (pData, textStatus, jqXHR) {
                if (pData) {
                    var data = eval("(" + pData + ")");
                    var pContent = "Bạn đã hoàn thành xong bình chọn của dự án này";
                    if (data.IsSuccessfull) {
                        $.CAlert.Success({
                            Title: "Lưu kết quả",
                            Content: pContent
                        }, function () {
                            var BINH_CHON_6SAO = $.GetCookie("BINH_CHON_6SAO");

                            if (BINH_CHON_6SAO) {
                                BINH_CHON_6SAO += $.string.Format(";{0}_{1}", pID, MEMBER_ID);
                            }
                            else
                                BINH_CHON_6SAO = $.string.Format("{0}_{1}", pID, MEMBER_ID);
                            $.SetCookie("BINH_CHON_6SAO", BINH_CHON_6SAO, 360);
                            location.href = "../../Views/Research/ResearchDetail.aspx?ID=" + pID;

                        });
                    }
                    else {
                        $.CAlert.Error({
                            Title: "Thông báo",
                            Content: data.Description
                        }, function () {
                            $research_item.find("img.img_research_captcha").attr("src", "/views/Captcha/ImageCaptcha.ashx?" + $.GuidGenerator());
                            $research_item.find("input.research_captcha").focus().select();
                        });
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    Chart: {
        Load: function (pID, callback) {
            var $research_item = $(".research_item[data-id='" + pID + "']");
            var chartID = "content_detail_chart_" + pID;
            var height = $research_item.find(".content-main").height() - 42;
            var ret = ''
            + '<div class="research_detail_title">KẾT QUẢ BÌNH CHỌN</div>'
            + '<div style="width: 500px; height:600px;" id="' + chartID + '"></div>'
            + '<div style="clear:both;overflow:hidden;">'
                + '<div class="_mark">Điểm tích lũy: <strong>100</strong></div>'
                + '<div class="_endDate"><span>Ngày kết thúc:</span> <span>31/01/2013</span></div> '
            + '</div>'
            + '';
            $research_item.find(".content_detail").html(ret);

            $.Ajax({
                url: "../Research/Service/ResearchService.asmx/GetChartData",
                type: 'POST',
                data: { pProjectID: pID },
                beforeSend: function () {
                },
                success: function (data, textStatus, xhr) {
                    if (data) {
                        data = $.findInXml(data);
                        data = eval("(" + data + ")");
                        var categories = [];
                        var series = [];
                        var temp = {};
                        $.each(data, function (index, item) {
                            if (typeof temp[item.Name] == "undefined") {
                                temp[item.Name] = {};
                                temp[item.Name].name = "";
                                temp[item.Name].data = [];
                            }

                            temp[item.Name].name = item.Name;
                            temp[item.Name].data.push(item.Percent);

                            if ($.inArray(item.GroupName, categories) == -1)
                                categories.push(item.GroupName);
                        });
                        $.each(temp, function (key, item) {
                            series.push(item);
                        });
                        var chart = new CChart({
                            chart: {
                                renderTo: "content_detail_chart_" + pID,
                                type: 'bar'
                            },
                            xAxis: {
                                categories: categories,
                                title: {
                                    text: null
                                },
                                gridLineWidth: 1
                            },
                            yAxis: {
                                min: 0,
                                max: 100,
                                title: {
                                    text: '',
                                    align: 'high'
                                },
                                labels: {
                                    overflow: 'justify'
                                }
                            },
                            series: series
                        });
                        chart.Init();
                        if (typeof callback == "function") {
                            callback();
                        }
                    }
                },
                error: function (xhr, textStatus, errorThrown) { }
            });

        }
    },
    GetCloundTag: function (newsID) {
        var pData = '{' + $.string.Format('"Context":"{0}"', '6SAO') + '}';
        var thisObj = this;
        $.ajax({
            url: '../TagCloud/Service/ClounbTagService.asmx/GetList',
            type: 'POST',
            data: pData,
            cache: false,
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (pData, textStatus, jqXHR) {
                if (pData !== null)
                    if (pData.d !== null) {
                        var data = eval("(" + pData.d + ")");
                        thisObj.BuildCloundTab(data);
                    }

            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });

    },
    BuildCloundTab: function (data) {
        var objThis = this;
        var pattern = '<a href="../TagCloud/{1}">{2}</a>&nbsp;&nbsp;';
        var htmlContent = "";
        $.each(data, function (index, item) {
            if (index == 13) return false;
            htmlContent += $.string.Format(pattern, objThis.GetRandom(1, 3), item.ID, item.Text);
        });
        $(".project_tags_content").html(htmlContent);
    },
    ScrollTo: function () {
        window.scrollTo(0, 150);
    },
    GetRandom: function (min, max) {
        return Math.round((Math.random() * (max - min)) + min);
    }
};

var _count = -1;
$(function () {
    Axis.View.Research.List.Init();
    NavigationActive(0);
    Axis.View.Research.List.ScrollTo();
});

function SaveServey(pQuesKey, pID) {
    Axis.View.Research.List.SaveServey(pQuesKey, pID);
}
function ResearchCaptchaRefresh(elm) {
    $(elm).prev("img").attr("src", "/views/Captcha/ImageCaptcha.ashx?" + $.GuidGenerator());
}
function TextTruncate() {
    $(".content_1").find(".subtitle").textTruncate(1190);
    $(".content_2").find(".subtitle").textTruncate(690);
    $(".content_3").find(".subtitle").textTruncate(570);
    $(".content_4").find(".subtitle").textTruncate(690);
    $(".content_5").find(".subtitle").textTruncate(550);
    $(".content_6").find(".subtitle").textTruncate(690);
    $(".content_7").find(".subtitle").textTruncate(730);
    $(".content_8").find(".subtitle").textTruncate(1100);
    $(".content_9").find(".subtitle").textTruncate(400);
}